package be.jabapage.snooker.service.importation.impl;

import java.io.Serializable;

import org.apache.commons.lang.Validate;

import be.jabapage.snooker.exception.EntityNotFoundException;
import be.jabapage.snooker.exception.MultipleInstanceFoundException;
import be.jabapage.snooker.exception.ProcessingException;
import be.jabapage.snooker.jdo.administration.Player;
import be.jabapage.snooker.service.administration.api.IPlayerService;
import be.jabapage.snooker.service.importation.api.IPlayerImportService;
import be.jabapage.snooker.service.overwriter.api.IPlayerOverwriter;

/**
 * @author axesq
 *
 */
public class PlayerImportService implements IPlayerImportService, Serializable {

	private static final long serialVersionUID = -5740987830134857808L;
	private final IPlayerService playerService;
	private final IPlayerOverwriter playerOverwriter;


	/**
	 * @param playerService
	 * @param playerOverwriter
	 */
	public PlayerImportService(final IPlayerService playerService, final IPlayerOverwriter playerOverwriter) {
		Validate.notNull(playerService);
		Validate.notNull(playerOverwriter);
		this.playerService = playerService;
		this.playerOverwriter = playerOverwriter;
	}


	/**
	 * {@inheritDoc}
	 */
	public void importPlayer(final Player player) throws ProcessingException {
		Validate.notNull(player);
		Validate.notNull(player.getName());
		try {
			Player databasePlayer = playerService.retrieve(player.getName());
			playerOverwriter.overwrite(databasePlayer, player);
			playerService.store(player);
		} catch (MultipleInstanceFoundException e) {
			throw new ProcessingException("Multiple players are found with this name", e);
		} catch (EntityNotFoundException e) {
			playerService.store(player);
		}
	}

}
